import { USER, STORAGE_KEY } from '../types'

export default {
  namespaced: true,
  state: {
    token: uni.getStorageSync(STORAGE_KEY.TOKEN) || '',
    userInfo: uni.getStorageSync(STORAGE_KEY.USER_INFO) || {},
  },
  mutations: {
    [USER.SET_TOKEN](state, token) {
      state.token = token
      uni.setStorageSync(STORAGE_KEY.TOKEN, token)
    },
    [USER.SET_USER_INFO](state, userInfo) {
      state.userInfo = userInfo
      uni.setStorageSync(STORAGE_KEY.USER_INFO, userInfo)
    },
    [USER.LOGOUT](state) {
      state.token = ''
      state.userInfo = {}
      uni.removeStorageSync(STORAGE_KEY.TOKEN)
      uni.removeStorageSync(STORAGE_KEY.USER_INFO)
    }
  },
  actions: {
    // 初始化用户状态
    initUserState({ commit }) {
      return new Promise((resolve) => {
        try {
          // 从storage读取token
          const token = uni.getStorageSync(STORAGE_KEY.TOKEN)
          if (token) {
            commit(USER.SET_TOKEN, token)
          }
          
          // 从storage读取用户信息
          const userInfo = uni.getStorageSync(STORAGE_KEY.USER_INFO)
          if (userInfo) {
            commit(USER.SET_USER_INFO, userInfo)
          }
          
          resolve()
        } catch (error) {
          console.error('初始化用户状态失败:', error)
          // 即使失败也resolve，避免阻塞启动流程
          resolve()
        }
      })
    },

    // 退出登录
    logout({ commit }) {
      return new Promise((resolve, reject) => {
        commit(USER.LOGOUT)
        resolve()
      })
    },
    saveToken({ commit }, token) {
      return new Promise((resolve, reject) => {
        try {
          var allToken = ''
          if (token.indexOf('Bearer') == 0){
            allToken = token
          }else {
            allToken = 'Bearer ' + token
          }
          
          if (allToken == 'Bearer '){
            allToken = ''
          }
          commit(USER.SET_TOKEN, allToken)
          resolve(allToken)
        } catch (error) {
          reject(error)
        }
      })
    },
    setUserInfo({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        try {
          commit(USER.SET_USER_INFO, userInfo || {})
          resolve(userInfo)
        } catch (error) {
          reject(error)
        }
      })
    }
  },
  getters: {
    token: state => state.token,
    userInfo: state => state.userInfo,
    isLogin: state => state.isLogin
  }
} 